

from django.db.models import Sum
from decimal import Decimal
from django.db.models import Q, F
import requests
import json
import datetime
from apps.common.utils.decrypt import *
from apps.merchant.item.dao import ItemDao
from apps.merchant.sku.dao import SkuDao
from apps.interface.client.dao import ClientDao
from apps.user.dao import UserDao
from apps.interface.advert.dao import AdvertDao
from apps.pay.order.dao import OrderDao
from apps.system.lessee.dao import LesseeDao
from apps.pay.recordIncomes.dao import RecordIncomesDao
from apps.system.payway.dao import PaywayDao

def function8():
    ''''同步所有商品的价格'''
    for item in ItemDao().findAll():
        skus = item.item_sku.all().order_by('sellingPrice')
        if skus.exists():
            sku = skus.first()
            ItemDao().update(item.id, {'sellingPrice': sku.sellingPrice, 'marketPrice': sku.marketPrice, 'discountPrice': sku.discountPrice})

def function7():
    try:
        ItemDao().findAll().filter(shop__isnull=True).update(shop=1)
        OrderDao().findAll().filter(shop__isnull=True).update(shop=1)
    except Exception as e:
        print('e', e)

def function6(name1,name2,name3):
    try:
        _objs = OrderDao().findAllSubOrder()
        for _obj in _objs:
            
            if _obj.expressageinfo:
                expressageinfoDict = json.loads(_obj.expressageinfo)
                if name1 == expressageinfoDict.get('expressageCompany'):
                    print('结果', _obj.orderId, expressageinfoDict.get('expressageCompany'))
                    expressageinfoDict.update({'expressageCompany': name2, 'code': name3})
                    # _obj.expressageinfo = json.dumps(expressageinfoDict)
                    # _obj.save()
    except Exception as e:
        print('e', e)

def function5():
    _obj = RecordIncomesDao().findOneByObjId(20673)
    receiptAccount = json.loads(_obj.receiptAccount)
    receiptAccount.update({'creditedBank': '中国工商银行股份有限公司','bankCode':'1001'})
    print('receiptAccount', receiptAccount)
    _obj.receiptAccount = json.dumps(receiptAccount)
    _obj.save()

def function4():
    try:
        # 平台总积分
        _users = UserDao().findAllUser().filter(incomes__gt=0)
        incomesAll = _users.aggregate(sums=Sum('incomes'))['sums'] or 0
        print('incomesAll', incomesAll)
        for user in _users:
            # print('用户', user.code, user.incomes)
            recordIncomes = RecordIncomesDao().findAll().filter(user=user, payway='incomes').first()
            if user.incomes != recordIncomes.balanceIncomes:
                print('余额', user.code, user.incomes, recordIncomes.balanceIncomes)

            recordIncomes = RecordIncomesDao().findAll().filter(user=user, payway='contributionValue').first()
            contributionValues = RecordIncomesDao().findAll().filter(user=user, payway='contributionValue', changeWay='add', money__gt=0).aggregate(sums=Sum('money'))['sums'] or 0
            if user.contributionValue != contributionValues:
                print('贡献值', user.code, user.contributionValue, recordIncomes.balanceIncomes, contributionValues)
                # user.contributionValue = contributionValues
                # user.save()

            recordIncomes = RecordIncomesDao().findAll().filter(user=user, payway='incomesLocked').first()
            incomesLockeds = RecordIncomesDao().findAll().filter(user=user, payway='incomesLocked', changeWay='add', moneyLocked__gt=0).aggregate(sums=Sum('moneyLocked'))['sums'] or 0
            if user.incomesLocked != incomesLockeds:
                print('锁仓补贴', user.code, user.incomesLocked, incomesLockeds)
                # user.incomesLocked = incomesLockeds
                # user.save()

        # recordIncomes = RecordIncomesDao().findAll().filter(payway='incomesLocked', changeWay='add', moneyLocked=0)
        # print('等于零的锁仓记录', recordIncomes.count())
        # for recordIncome in recordIncomes:
        #     recordIncomesForContributionValue = RecordIncomesDao().findAll().filter(shop__isnull=True, orderId = recordIncome.orderId, payway='contributionValue', changeWay='add', money__gt=0)
        #     if recordIncomesForContributionValue.exists():
        #         print('锁仓释放完的订单', recordIncome.orderId, '订单号相同的贡献值奖励订单', recordIncomesForContributionValue )
    except Exception as e:
        print('e', e)

def function1():
    print('function1')
    _users = UserDao().findAllUser()
    for user in _users:
        _list = UserDao().findAllUser().filter(parent=user).filter(rank__grade__gt=0)
        # print('粉丝以上级别人数', user.rank.grade, _list.count())
        if _list.count()>=2:
            if user.rank.grade<=1:
                print('异常：不是VIP的会员', user, user.rank.grade)
        else:
            if user.rank.grade>1:
                print('异常：', user,  user.rank.grade)
    

def function2():
    print('function2')
    try:
        _users = UserDao().findAllUser().filter(rank__grade__gt=1)
        _users.update(upRankTime=datetime.datetime.now())
    except Exception as e:
        print('e', e)
        
def function3():
    print('function3')
    try:
        money = Decimal(50000)
        payway = 'grossProfit'
        LesseeDao().subWallet(payway, money)
        data = {}
        data['scene'] = 'subIncomeFromAdmin'
        data['user'] = ''
        data['fromUser'] = 1
        data['orderId'] = ''
        data['money'] = money
        data['payway'] = payway
        data['changeWay'] = 'sub'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)

        payway = 'freePoolMonth'
        LesseeDao().addWallet(payway, money)
        data = {}
        data['scene'] = 'addIncomeFromAdmin'
        data['user'] = ''
        data['fromUser'] = 1
        data['orderId'] = ''
        data['money'] = money
        data['payway'] = payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)
    except Exception as e:
        print('e', e)


def replaceImageUrl():
    clients = ClientDao().findAll()
    print('items', clients.count())
    for item in clients:
        string = item.updateUrlForAndriod
        new_string = string.replace('zjyh.service.qly.plus', 'yhzb.service.zjyh888.com')
        item.updateUrlForAndriod = new_string

        if item.notify_url:
            string1 = item.notify_url
            new_string1 = string1.replace('zjyh.service.qly.plus', 'yhzb.service.zjyh888.com')
            item.notify_url = new_string1

        if item.logo:
            string2 = item.logo
            new_string2 = string2.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
            item.logo = new_string2

        if item.miniproUrl:
            string3 = item.miniproUrl
            new_string3 = string3.replace('zjyh.service.qly.plus', 'yhzb.service.zjyh888.com')
            item.miniproUrl = new_string3

        if item.baseUrl:
            string4 = item.baseUrl
            new_string4 = string4.replace('zjyh.service.qly.plus', 'yhzb.service.zjyh888.com')
            item.baseUrl = new_string4

        item.save()

    items = ItemDao().findAll().exclude(detaiΩlPhotosRichText='')
    print('items', items.count())
    for item in items:
        detailPhotosRichTextstr = item.detailPhotosRichText
        print('111', detailPhotosRichTextstr)
        new_string = detailPhotosRichTextstr.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        print('222', new_string)
        item.detailPhotosRichText = new_string

        coverPhotos = item.coverPhotos
        coverPhotos = coverPhotos.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        print('222', coverPhotos)
        item.coverPhotos = coverPhotos
        item.save()

    skus = SkuDao().findAll()
    for item in skus:
        coverUrl = item.coverUrl
        coverUrl = coverUrl.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        item.coverUrl = coverUrl

        item.save()

    users = UserDao().findAll()
    for item in users:
        avatarUrl = item.avatarUrl
        avatarUrl = avatarUrl.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        item.avatarUrl = avatarUrl
        item.save()

    adverts = AdvertDao().findAll()
    for item in adverts:
        coverUrl = item.coverUrl
        coverUrl = coverUrl.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        item.coverUrl = coverUrl
        item.save()

    orders = OrderDao().findAllMainOrder()
    for item in orders:
        content = item.content
        content = content.replace('oss.zjyh.qly.plus', 'oss.zjyh888.com')
        item.content = content
        item.save()

def handleItem6():
    for item in ItemDao().findAll():
        skus = item.item_sku.all()
        # print('skus', skus.count())
        sellingPrice = 0
        if skus.count() > 1:
            sellingPrice = skus.first().sellingPrice
            
            for sku in skus:
                print('多sku，价格', item.id, sku.sellingPrice)
            #     if sku.sellingPrice != sellingPrice:
            #         print('多sku，价格不同', item.id, sku.sellingPrice)
            # print('item', item.name)
        print('-------------------------')


def handleItem5():
    ItemDao().findAll().filter(Q(cate=7) | Q(cate=8) | Q(cate=9)| Q(cate=10)).update(cate=11)

def handleItem4():
    _skus = SkuDao().findAll().filter(coverUrl='')
    print('_skus', _skus.count())
    try:
        for sku in _skus:
            print('sku.coverUrl', sku.coverUrl)
            if not sku.coverUrl or sku.coverUrl != None:
                coverPhotoList = []
                if sku.item:
                    print('sku.item.coverPhotos', sku.item.coverPhotos)
                    coverPhotoList = json.loads(sku.item.coverPhotos)
                if len(coverPhotoList) > 0:
                    sku.coverUrl = coverPhotoList[0]
                    sku.save()
    except Exception as e:
        print('e', e)

def handleItem3():
    url = 'http://127.0.0.1:8001/api/merchant/itemForM/'
    headers = {'content-type': "application/json", 'Authorization': 'token bc1a7cb317256400d7e2fcf7c2e019a177f3f94b'}
    params = {
        'openshop': 17,
        'size': 1000,
        'isSingleSpec': 0
    }
    res = requests.get(url, params=params, headers=headers)
    resDict = json.loads(res.content)
    res = aesDecrypt(AESKey, resDict)
    _list = res.get('list')
    # print('拉取商品', res)
    # print('item', len(_list))
    for item in _list:
        _items = ItemDao().findAll().filter(name=item.get('itemName'))
        print('items个数', _items.count())
        print('skuList', item.get('skuList'))
        for sku in item.get('skuList'):
            skuData = {}
            skuData['specValues'] = sku.get('specValues')
            skuData['coverUrl'] = sku.get('cover')
            skuData['marketPrice'] = sku.get('marketPrice')
            skuData['sellingPrice'] = sku.get('sellingPrice')
            skuData['stock'] = '999'
            skuData['item'] = _items.first().id
            SkuDao().create(skuData)

    _items = ItemDao().findAll().filter(item_sku__isnull=True)
    for item in _items:
        print('产品名称', item.name)
        _skus = SkuDao().findAll().filter(item=item)
        print('_skus', _skus.count())
    print('_items', _items.count())




def handleItem2():
    # url = 'https://axh.service.sailami.top/api/merchant/itemForM/'
    url = 'http://127.0.0.1:8001/api/merchant/itemForM/'
    headers = {'content-type': "application/json", 'Authorization': 'token bc1a7cb317256400d7e2fcf7c2e019a177f3f94b'}
    params = {
        'openshop': 17,
        'size': 1000,
        'isSingleSpec': 0
    }
    res = requests.get(url, params=params, headers=headers)
    resDict = json.loads(res.content)
    res = aesDecrypt(AESKey, resDict)
    _list = res.get('list')
    print('拉取商品', res)
    print('item', _list[0])
    for item in _list:
        data = {}
        data['name'] = item.get('itemName')

        if item.get('shopinCate'):
            if item.get('shopinCate') == 71:
                data['cate'] = 7
            elif item.get('shopinCate') == 72:
                data['cate'] = 8
            elif item.get('shopinCate') == 73:
                data['cate'] = 9
            elif item.get('shopinCate') == 74:
                data['cate'] = 10
            elif item.get('shopinCate') == 75:
                data['cate'] = 11
        data['status'] = 1
        data['checkStatus'] = 'PASS'
        data['isOnlinePay'] = 1
        data['isSingleSpec'] = item.get('isSingleSpec')
        covers = item.get('coverPhotoList')
        coverUrls = []
        for file in covers:
            coverUrls.append(file.get('coverUrl'))
        data['coverPhotos'] = json.dumps(coverUrls)
        if item.get('detailPhotosRichText'):
            data['detailPhotosRichText'] = item.get('detailPhotosRichText')
        else:
            print('detailPhotoList')
            _files = item.get('detailPhotoList')
            detailstr = ''
            for file in _files:
                detailstr + '<img src="' + file.get('coverUrl') + '">'
            data['detailPhotosRichText'] = '<p>' + detailstr + '</p>'
        itemobj = ItemDao().create(data)
        if item.get('isSingleSpec') == 1:
            skuData = {}
            skuData['specValues'] = '[{"specName":"规格","name":"默认"}]'
            skuData['coverUrl'] = item.get('coverUrl')
            skuData['marketPrice'] = item.get('marketPrice')
            skuData['sellingPrice'] = item.get('sellingPrice')
            skuData['stock'] = item.get('totalStock') if item.get('totalStock')!='0' else '999'
            skuData['item'] = itemobj.id
            print('skuData', skuData)
            SkuDao().create(skuData)
        else:
            for sku in item.get('skuList'):
                skuData = {}
                skuData['specValues'] = sku.get('specValues')
                skuData['coverUrl'] = sku.get('coverUrl')
                skuData['marketPrice'] = sku.get('marketPrice')
                skuData['sellingPrice'] = sku.get('sellingPrice')
                skuData['stock'] = sku.get('stock') if sku.get('stock')!='0' else '999'
                skuData['item'] = itemobj.id
                SkuDao().create(skuData)
def handleItem1():
    _items = ItemDao().findAll().filter(cate__isnull=True)
    _items = _items.filter(name__contains='兔年金币')
    for item in _items:
        print('产品名称', item.name)
        # print('产品分类', item.cate)
    print('_items', _items.count())
    # _items.update(cate=12)